from django.conf import settings
from django.contrib.auth.models import User
from django.db.models import *
from django.template.defaultfilters import slugify
from django.utils.safestring import mark_safe
from pyplog.artists.models import Artist, Profession
from pyplog.blog.utils import PublishedManager
from pyplog.config import config
from pyplog.image_processors import get_image_obj, resize_to_fit, square_bw_thumbnail

class GenericPhotoAttribute(Model):
	title = CharField(max_length = 64)
	slug = SlugField(unique = True)
	
	class Meta:
		abstract = True
		
	def __unicode__(self):
		return self.title
	
	@permalink
	def get_absolute_url(self):
		return ("key-photos", (), { "key" : self._meta.object_name.lower(), "slug" : self.slug })
	
	@permalink
	def get_feed_url(self):
		return ("photo-feed", (), { "url" : self._meta.object_name.lower() + "/" + self.slug })

class PublicManager(Manager):
	"""
	A custom manager to return only public galleries.
	"""
	def get_query_set(self):
		return super(PublicManager, self).get_query_set().filter(password = "")

class Gallery(GenericPhotoAttribute):
	password = CharField(max_length = 32, blank = True, help_text = "Leave empty for public galleries")
	position = PositiveSmallIntegerField(default = 1, help_text = "Higher number means higher position in galleries index")
	
	objects = Manager()
	public_objects = PublicManager()
	
	class Meta:
		ordering = ["-position"]
		verbose_name = "gallery"
		verbose_name_plural = "galleries"
	
	@property
	def featured_photos(self):
		return self.photos.all()[:config.gallery_featured_photos]
	
	@property
	def photoset_description(self):
		return mark_safe("All photos in the <i>" + self.title + "</i> gallery.")
	
class License(GenericPhotoAttribute):
	url = URLField(help_text = "URL pointing to a website with the license text")
	@property
	def photoset_description(self):
		return mark_safe("All photos published under the <a href='" + self.url + "'>" + self.title + "</a> license")
	
	@classmethod
	def add_defaults(cls, sender, **kwars):
		"""
		Adds a useful set of licenses.
		"""
		defaults = {
			"Public domain" : "http://creativecommons.org/licenses/publicdomain/",
			"CC BY-NC-ND 3.0" : "http://creativecommons.org/licenses/by-nc-nd/3.0/",
			"CC BY-SA 3.0" : "http://creativecommons.org/licenses/by-sa/3.0/",
			"GFDL" : "http://www.gnu.org/copyleft/fdl.html",
			"Artistic" : "http://www.opensource.org/licenses/artistic-license-2.0.php",
		}
		print "Adding default licenses... "
		for license in defaults:
			try:
				cls.objects.create(title = license, slug = slugify(license), url = defaults[license])
			except:
				pass
module = __import__("pyplog.photos.models", fromlist = [None], level = 0)
signals.post_syncdb.connect(License.add_defaults, sender = module)
	
class Location(GenericPhotoAttribute):
	@property
	def photoset_description(self):
		return mark_safe("All photos shot at: " + self.title)

class Tag(GenericPhotoAttribute):
	@property
	def photoset_description(self):
		return mark_safe("All photos with the " + self.title + " tag")
	
class Contribution(Model):
	artist = ForeignKey(Artist, related_name = "contributions")
	photo = ForeignKey("Photo", related_name = "contributions")
	role = ForeignKey(Profession)
	
	def __unicode__(self):
		return self.artist.name + " as " + str(self.role) + " on " + self.photo.title
	
class Photo(Model):
	title = CharField(max_length = 64)
	slug = SlugField(unique = True)
	description = TextField(blank = True)
	published = DateTimeField()

	source_image = ImageField(upload_to = "img/photos/source-images", help_text = "Image should be larger than 700px on at least one side and must be larger than 80px on either side")
	
	gallery = ForeignKey(Gallery, related_name = "photos")
	license = ForeignKey(License, blank = True, null = True, related_name = "photos")
	location = ForeignKey(Location, blank = True, null = True, related_name = "photos")
	tags = ManyToManyField(Tag, blank = True, null = True, related_name = "photos")
	
	contributors = ManyToManyField(Artist, through = Contribution, related_name = "photos")
	
	public_objects = PublishedManager()
	all_objects = Manager()
	
	@property
	def detail_image(self):
		return "img/photos/detail-images/" + self.slug + ".jpg"
	
	@property
	def thumbnail_image(self):
		return "img/photos/thumbnail-images/" + self.slug + ".jpg"
	
	class Meta:
		ordering = ["-published"]
		
	def __unicode__(self):
		return self.title
	
	@permalink
	def get_absolute_url(self):
		return ("photo-detail", (), { "slug" : self.slug })
	
	def save(self):
		source_image = get_image_obj(self.source_image)
		detail_image = resize_to_fit(source_image.copy())
		thumbnail_image = square_bw_thumbnail(detail_image.copy())
		detail_image.save(settings.MEDIA_ROOT + self.detail_image, quality = 90)
		thumbnail_image.save(settings.MEDIA_ROOT + self.thumbnail_image, quality = 75)
		super(Photo, self).save()
